{% extends "base.html" %}
{% block content %}
    <h2>添加用户</h2>
    <form method="POST" onsubmit="return validateAddForm(event)">
        <div class="form-group">
            <label>姓名：</label>
            <input type="text" name="name" required>
        </div>
        <div class="form-group">
            <label>邮箱：</label>
            <input type="email" name="email" id="add-email" required>
            <span id="add-email-error" style="color: red; display: none;"></span>
        </div>
        <div class="form-group">
            <label>年龄：</label>
            <input type="number" name="age" required>
        </div>
        <button type="submit">添加用户</button>
    </form>

    <script>
        // 异步校验邮箱（添加场景）
        async function checkAddEmail() {
            const email = document.getElementById('add-email').value.trim();
            const errorSpan = document.getElementById('add-email-error');
            if (!email) {
                errorSpan.style.display = 'none';
                return true;
            }

            try {
                const response = await fetch(`/check_email?email=${email}`);
                const data = await response.json();
                if (data.exists) {
                    errorSpan.textContent = "该邮箱已被使用";
                    errorSpan.style.display = 'block';
                    return false;
                } else {
                    errorSpan.style.display = 'none';
                    return true;
                }
            } catch (error) {
                console.error("校验失败：", error);
                errorSpan.textContent = "校验出错，请稍后重试";
                errorSpan.style.display = 'block';
                return false;
            }
        }

        // 表单提交校验
        async function validateAddForm(event) {
            const isEmailValid = await checkAddEmail();
            if (!isEmailValid) {
                event.preventDefault();
                return false;
            }
            return true;
        }

        // 输入框实时校验（可选，提升体验）
        document.getElementById('add-email').addEventListener('input', () => {
            checkAddEmail();
        });
    </script>
{% endblock %}
{% block list %}
    <h2>用户列表</h2>
    <table>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>年龄</th>
            <th>操作</th>
        </tr>
        {% for user in users %}
        <tr>
            <td>{{ user[0] }}</td>
            <td>{{ user[1] }}</td>
            <td>{{ user[2] }}</td>
            <td>{{ user[3] }}</td>
            <td>
                <a href="{{ url_for('edit', id=user[0]) }}">编辑</a> |
                <a href="{{ url_for('delete', id=user[0]) }}" onclick="return confirm('确认删除？')">删除</a>
            </td>
        </tr>
        {% endfor %}
    </table>
{% endblock %}
